﻿package br.senai.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.senai.entidade.Sessao;

/**
 * Classe que verifica se o o usu�rio est� logado em uma sess�o.
 */
@WebFilter(filterName="AutenticacaoFilter",urlPatterns="/pages/*")
public class AutenticacaoFilter implements Filter{

	private FilterConfig config = null;
	private ServletContext servletContext = null;

	public void init(FilterConfig filterConfig) throws ServletException{

		config = filterConfig;
		servletContext = config.getServletContext();

	}

	/**
	 * Se o usu�rio n�o est� em uma sess�p ele � redirecionado
	 * para a p�gina de login.
	 */
	public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws IOException, ServletException{

		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		//HttpSession session = httpRequest.getSession();

		Sessao sessao = (Sessao) httpRequest.getSession().getAttribute("sessaoKey"); //(Sessao)session.getAttribute("sessaoKey");

		//Se o usuario nao esta na sessao, nao estao logado...
		if(sessao == null){
			//Redireciona p/ pagina de login 
			httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsf");
		}
		else{
			chain.doFilter(request,response);
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
}